<template>
  <div class="mod-config">
    <div v-if="member">
      <el-form :inline="true" :model="dataForm" @keyup.enter.native="search()" ref="dataForm">
        <el-form-item>
          <el-input v-model="dataForm.id" placeholder="心愿单编号"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="dataForm.partnerName" placeholder="学生姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="dataForm.title" placeholder="心愿名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="dataForm.captainName" placeholder="团队心愿领取人"></el-input>
        </el-form-item>
        <el-form-item label="心愿类型：">
          <el-select v-model="dataForm.wishType" placeholder="请选择">
            <el-option
              v-for="item in useroption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="心愿状态：">
          <el-select v-model="dataForm.wishStatus" placeholder="请选择标签">
            <el-option
              v-for="item in useroption1"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search()">查询</el-button>
          <el-button type="primary"  @click="modifyWish()">新增</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="dataList"
        border
        v-loading="dataListLoading"
        style="width: 100%;"
      >
        <el-table-column prop="id" header-align="center" align="center" label="心愿单编号"></el-table-column>
        <el-table-column prop="partnerName" header-align="center" align="center" label="学生姓名"></el-table-column>
        <el-table-column prop="partnerId" header-align="center" align="center" label="伴学对象编号"></el-table-column>
        <el-table-column prop="title" header-align="center" align="center" label="心愿名称"></el-table-column>
        <el-table-column header-align="center" align="center" label="心愿类型">
          <template slot-scope="scope">
            {{ scope.row.wishType === 1?'个人心愿':'' }}
            {{ scope.row.wishType === 2?'团队心愿':'' }}
          </template>
        </el-table-column>
        <el-table-column prop="captainName" header-align="center" align="center" label="团队心愿领取人"></el-table-column>
        <el-table-column header-align="center" align="center" label="心愿缩略图">
          <template slot-scope="scope">
            <img :src="scope.row.wishInfo" alt="">
          </template>
        </el-table-column>
        <el-table-column prop="bookId" header-align="center" align="center" label="心愿状态">
          <template slot-scope="scope">
            {{ scope.row.wishStatus === 1?'进行中 ':'' }}
            {{ scope.row.wishStatus === 3?'寄送中':'' }}
            {{ scope.row.wishStatus === 2?'助力完成':'' }}
            {{ scope.row.wishStatus === 5?'已送达':'' }}
          </template>
        </el-table-column>
        <el-table-column prop="targetCredit" header-align="center" align="center" label="所需学分"></el-table-column>
        <el-table-column prop="donateCredit" header-align="center" align="center" label="已捐学分"></el-table-column>
        <el-table-column header-align="center" align="center" label="申请理由">
          <template slot-scope="scope">
            <img :src="scope.row.whyUrl" alt="">
          </template>
        </el-table-column>
        <el-table-column prop="teacherName" header-align="center" align="center" label="伴学老师"></el-table-column>
        <el-table-column prop="teacherId" header-align="center" align="center" label="伴学老师编号"></el-table-column>
        <el-table-column prop="teacherWhy" show-overflow-tooltip="true" header-align="center" align="center" label="推荐理由"></el-table-column>
        <el-table-column prop="gmtCreated" header-align="center" align="center" label="创建时间"></el-table-column>
        <el-table-column prop="gmtUpdate" header-align="center" align="center" label="更新时间"></el-table-column>
        <el-table-column fixed="right" header-align="center" align="center" label="操作" width="150px">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="modifyWish(scope.row)">修改</el-button>
            <el-button v-if="scope.row.wishStatus === 2" type="text" size="small" @click="setSendInfo(scope.row, 1)">添加寄送信息</el-button>
            <el-button v-if="scope.row.wishStatus === 3||scope.row.wishStatus === 5" type="text" size="small" @click="setSendInfo(scope.row, 2)">修改寄送信息</el-button>
            <el-button v-if="scope.row.wishStatus === 3" type="text" size="small" @click="setFeedback(scope.row, 1)">添加反馈信息</el-button>
            <el-button v-if="scope.row.wishStatus === 5" type="text" size="small" @click="setFeedback(scope.row, 2)">修改反馈信息</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper"
      ></el-pagination>

      <!--添加寄送信息s-->
      <el-dialog
        :close-on-click-modal="false"
        :visible.sync="visible1"
        :title="isAddSend?'添加寄送信息':'修改寄送信息'"
      >
        <el-form
          :model="dataForm1"
          ref="dataForm1"
          label-width="150px"
        >
          <el-form-item label="上传寄送图片">
            <el-upload
              :limit="1"
              :action="url"
              list-type="picture-card"
              :before-upload="handlePictureCardPreview"
              :on-success="PictureCardPreview"
              :file-list="fileLists"
              :on-remove="handleRemove"
              :on-exceed="overNum"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <div style="color: #999;">只能上传1张图片且图片必须是546*270</div>
          </el-form-item>
          <el-form-item label="寄送时间:">
            <el-date-picker
              style="width:220px;"
              v-model="dataForm1.sendTime"
              type="date"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择寄送时间"
            ></el-date-picker>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="visible1 = false">取消</el-button>
          <el-button type="primary" @click="setSend" :loading="submitloading">确定</el-button>
        </span>
      </el-dialog>
      <!--添加寄送信息e-->

      <!--添加反馈信息s-->
      <el-dialog
        :close-on-click-modal="false"
        :visible.sync="visible2"
        :title="isAddFeed?'添加反馈信息':'修改反馈信息'"
      >
        <el-form
          :model="dataForm2"
          ref="dataForm1"
          label-width="150px"
          :rules="rules"
        >
          <el-form-item label="上传反馈图片">
            <el-upload
              :limit="2"
              :action="url"
              list-type="picture-card"
              :before-upload="handlePictureCardPreview1"
              :on-success="PictureCardPreview1"
              :file-list="fileLists1"
              :on-remove="handleRemove1"
              :on-exceed="overNum1"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <div style="color: #999;">最多上传2张图片且图片必须是330*270</div>
          </el-form-item>
          <el-form-item label="感谢语">
            <el-input v-model="dataForm2.thanksNote" placeholder="添加感谢语"  type="textarea" :rows="4"></el-input>
          </el-form-item>
          <el-form-item label="送达时间:">
            <el-date-picker
              style="width:220px;"
              v-model="dataForm2.servedTime"
              type="date"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择送达时间"
            ></el-date-picker>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="visible2 = false">取消</el-button>
          <el-button type="primary" @click="setFeed" :loading="submitloadingFeed">确定</el-button>
        </span>
      </el-dialog>
      <!--添加反馈信息e-->

    </div>
    <modify ref="wishInfo" @refreshDataList="getDataList"></modify>
  </div>
</template>

<script>
  import QRCode from "qrcode";
  import Modify from './modify'
  export default {
    data() {
      return {
        submitloadingFeed: false,
        submitloading: false,
        isAddSend: true,
        isAddFeed: true,
        sendtype: 1,
        backtype: 1,
        url: '',
        fileLists: [],
        fileLists1: [],
        member: true,
        visible2: false,
        visibleIntegralList: false,
        dataForm1: {},
        rules: {
          labelIds: [
            { required: true, message: '请选择标签', trigger: 'blur' }
          ],
        },
        zanConfig: 0,
        visible1: false,
        useroption: [
          {
            value: null,
            label: '全部'
          },
          {
            value: '1',
            label: '个人心愿'
          },
          {
            value: '2',
            label: '团队心愿'
          }
        ],
        useroption1: [
          {
            value: null,
            label: '全部'
          },
          {
            value: '1',
            label: '进行中'
          },
          {
            value: '3',
            label: '寄送中'
          },
          {
            value: '2',
            label: '助力完成'
          },
          {
            value: '5',
            label: '已送达'
          }
        ],
        dataForm: {},
        dataForm2: {},
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        appLabel: [],
        visibleResource: false,
        forbidDetail: {},
        actionImages: [],
        resourceType: ''
      }
    },
    components: {
      Modify
    },
    mounted() {
      this.url = this.$http.adornUrl(
        `/partner/partnerwish/upload?token=${this.$cookie.get('token')}`
      )
    },
    activated() {
      this.getDataList()
    },
    methods: {
      overNum() {
        this.$message.error('只能上传1张图片!')
      },
      overNum1() {
        this.$message.error('最多上传2张图片!')
      },
      search() {
        this.pageIndex = 1
        this.getDataList()
      },
      handlePictureCardPreview: function (file) {
        const isJPG = file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/gif'
        if (!isJPG) {
          this.$message.error('只能上传是图片!')
        }
        const isSize = new Promise(function(resolve, reject) {
          let width = 546;
          let height = 270;
          let _URL = window.URL || window.webkitURL;
          let img = new Image();
          img.onload = function() {
            let valid = img.width == width && img.height == height;
            valid ? resolve() : reject();
          };
          img.src = _URL.createObjectURL(file);
        }).then(
          () => {
            return file;
          },
          () => {
            this.$message.error("上传的图片必须是546*270!");
            return Promise.reject();
          }
        );
        return isJPG && isSize
      },
      handlePictureCardPreview1: function (file) {
        const isJPG = file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/gif'
        if (!isJPG) {
          this.$message.error('只能上传是图片!')
        }
        const isSize = new Promise(function(resolve, reject) {
          let width = 330;
          let height = 270;
          let _URL = window.URL || window.webkitURL;
          let img = new Image();
          img.onload = function() {
            let valid = img.width == width && img.height == height;
            valid ? resolve() : reject();
          };
          img.src = _URL.createObjectURL(file);
        }).then(
          () => {
            return file;
          },
          () => {
            this.$message.error("上传的图片必须是330*270!");
            return Promise.reject();
          }
        );
        return isJPG && isSize
      },
      PictureCardPreview: function (response, file, fileList) {
        this.fileLists = fileList
      },
      handleRemove: function (file, fileList) {
        this.fileLists = fileList
      },
      PictureCardPreview1: function (response, file, fileList) {
        this.fileLists1 = fileList
      },
      handleRemove1: function (file, fileList) {
        this.fileLists1 = fileList
      },
      // 获取数据列表
      getDataList() {
        // this.dataListLoading = true
        this.dataForm.page = this.pageIndex
        this.dataForm.limit = this.pageSize
        this.$http({
          url: this.$http.adornUrl('/partner/partnerwish/list'),
          method: 'get',
          params: this.$http.adornParams(this.dataForm)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$refs['dataForm'].resetFields()
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
            let len = data.page.list.length;
            for (let i = 0; i < len; i++) {
              let codeUrl = this.dataList[i].wxQrcode || "";
              let opts = {
                errorCorrectionLevel: "H",
                type: "image/jpeg",
                rendererOpts: {
                  quality: 0.3
                }
              };
              QRCode.toDataURL(codeUrl, opts, (err, url) => {
                this.dataList[i].codeImg = url;
              });
            }
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      setSendInfo(data, type) {
        this.fileLists = []
        this.isAddSend = type === 1
        this.visible1 = true
        this.dataForm1 = JSON.parse(JSON.stringify(data))
        if(this.dataForm1.sendUrl) {
          this.fileLists = [
            {
              name:'1',
              url: this.dataForm1.sendUrl
            }
          ]
        }
        if(this.dataForm1.sendTime.indexOf('2000')>-1) {
          this.dataForm1.sendTime = ''
        }
      },
      setFeedback(data, type) {
        this.fileLists1 = []
        this.isAddFeed = type === 1
        this.visible2 = true
        this.dataForm2 = JSON.parse(JSON.stringify(data))
        if(this.dataForm2.feedbackUrl) {
          this.dataForm2.feedbackUrl.split(',').map((item)=> {
            this.fileLists1.push({
              name: item,
              url: item
            })
          })
        }
        if(this.dataForm2.servedTime.indexOf('2000')>-1) {
          this.dataForm2.servedTime = ''
        }
      },
      setSend() {
        const newArr = [], obj = {}
        this.fileLists.map((item)=> {
          if(item.response&&item.response.url){
            newArr.push(item.response.url)
          }else if(item.url){
            newArr.push(item.url)
          }
        })
        obj.sendUrl = newArr.join(',')
        obj.id = this.dataForm1.id
        obj.partnerId = this.dataForm1.partnerId
        obj.sendTime = this.dataForm1.sendTime
        obj.wishStatus = 3
        if(!obj.sendUrl) {
          this.$message.error('请上传寄送图片');
          return false
        }
        if(!obj.sendTime) {
          this.$message.error('请选择寄送时间');
          return false
        }
        this.submitloading = true
        this.$http({
          url: this.$http.adornUrl('/partner/partnerwish/updateSendInfo'),
          method: 'post',
          data: this.$http.adornData(obj)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.submitloading = false
            this.visible1 = false
            this.$message.success('操作成功')
            this.search()
          } else {
            this.submitloading = false
            this.$message.error(data.msg)
          }
        })
      },
      setFeed() {
        const newArr = [], obj = {}
        this.fileLists1.map((item)=> {
          if(item.response&&item.response.url){
            newArr.push(item.response.url)
          }else if(item.url){
            newArr.push(item.url)
          }
        })
        obj.feedbackUrl = newArr.join(',')
        obj.id = this.dataForm2.id
        obj.partnerId = this.dataForm2.partnerId
        obj.thanksNote = this.dataForm2.thanksNote
        obj.servedTime = this.dataForm2.servedTime
        obj.wishStatus = 5
        if(!obj.feedbackUrl) {
          this.$message.error('请上传反馈图片');
          return false
        }
        if(!obj.servedTime) {
          this.$message.error('请选择送达时间');
          return false
        }
        if(!obj.thanksNote) {
          this.$message.error('请填写感谢语');
          return false
        }
        this.submitloadingFeed = true
        this.$http({
          url: this.$http.adornUrl('/partner/partnerwish/updateFeedbackInfo'),
          method: 'post',
          data: this.$http.adornData(obj)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.submitloadingFeed = false
            this.visible2 = false
            this.$message.success('操作成功')
            this.search()
          } else {
            this.submitloadingFeed = false
            this.$message.error(data.msg)
          }
        })
      },
      modifyWish(data) {
        this.$nextTick(() => {
          this.$refs.wishInfo.init(data || '')
        })
      },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 新增 / 修改
      lookOrCheck(id) {
        this.member = false
        this.$nextTick(() => {
          this.$refs.integralList.initIntegral(id)
        })
      },
      showMember() {
        this.member = true
      },
      download() {
        this.dataForm.page = this.pageIndex
        this.dataForm.limit = this.pageSize
        this.$http({
          url: this.$http.adornUrl("/point/userRewardPoint/download"),
          method: "get",
          params: this.$http.adornParams(this.dataForm),
          headers: {
            "Content-Type": "application/json; application/octet-stream"
          },
          responseType: "arraybuffer"
        }).then(({ data }) => {
          const blob = new Blob([data], { type: "application/vnd.ms-excel" });
          const downloadElement = document.createElement("a");
          const href = window.URL.createObjectURL(blob);
          downloadElement.href = href;
          downloadElement.download = "会员积分列表.xls";
          document.body.appendChild(downloadElement);
          downloadElement.click();
          document.body.removeChild(downloadElement); // 下载完成移除元素
          window.URL.revokeObjectURL(href); // 释放掉blob对象
        });
      }
    }
  }
</script>
<style>
  .margin_10{
    margin-bottom: 10px;
  }
  .text_r{
    text-align: right;
    padding-right: 15px;
  }
  .inineBlock{
    display: inline-block;
  }
  img{
    width: 100%;
    height: auto;
  }
  .imgList{
    display: flex;
    flex-wrap: wrap;
  }
  .imgList>div{
    width: 80px;
    margin: 5px 15px 5px 0;
  }
</style>
